//
//  MoveMenuView.m
//  MoveBtn
//
//  Created by limaohuyu on 2020/9/24.
//

#import "MoveMenuView.h"
#define kKeyWindow [[[UIApplication sharedApplication] delegate] window]
#define kScreenBounds [UIScreen mainScreen].bounds
#define keyScreenWidth [UIScreen mainScreen].bounds.size.width
#define keyScreenHeight [UIScreen mainScreen].bounds.size.height

//获取状态栏的高度
#define SRARUS_HEIGHT [UIApplication sharedApplication].statusBarFrame.size.height
//安全区底部高度
#define SAFEARWA_BOTTOM_HEIGHT (iPhoneX ? 34 : 0)
//状态栏+导航栏高度
#define  SRARUSBAR_NAVIGATIONBAR_HEIGHT  (iPhoneX ? 88.f : 64.f)
//tabar高度
#define  SRARUSBAR_TABAR_HEIGHT  (iPhoneX ? 83.f : 49.f) 

//根据安全区判断
#define iPhoneX \
({BOOL isPhoneX = NO;\
if (@available(iOS 11.0, *)) {\
isPhoneX = [[UIApplication sharedApplication] delegate].window.safeAreaInsets.bottom > 0.0;\
}\
(isPhoneX);})




#define MENUVIEW_HEIGHT 54

//Item之前间距
#define MENUVIEW_ITEM_SPACE 10
//背景View 超出的距离
#define MENUVIEW_BGVIEW_BEYOND 20


@interface MoveMenuAction ()

@property(nonatomic,copy)NSString * title ;
@property (nonatomic,strong) UIImage  * image ;

@property (nonatomic,copy) UIButton*(^itemHandler)(void)  ;

@end

@implementation MoveMenuAction


+(instancetype)actionWithTitle:(NSString *)title image:(UIImage*)image handler:(void (^)(void ))handler{
    
    MoveMenuAction *action = [MoveMenuAction new];
    action.title = title;
    action.image = image;
    action.handler = handler;
    return  action;
    
}

+(instancetype)actionWithItemHandler:(UIButton * (^)(void))itemHandler{
    MoveMenuAction *action = [MoveMenuAction new];
    action.title = @"";
    action.image = nil;
    action.itemHandler = itemHandler;
    return  action;
}
@end

@interface MoveMenuView ()
{
    CGPoint beginPoint;
    CGFloat rightMargin;
    CGFloat leftMargin;
    CGFloat topMargin;
    CGFloat bottomMargin;
    CGMutablePathRef pathRef;
    dispatch_source_t _timer ;
    
}
@property (nonatomic,strong) UIView  * bgView ;
@property (nonatomic,strong) UIView  * contentView ;

@property (nonatomic,strong) UIButton *centerBtn;
@property (nonatomic,weak) UIView  * supView ;
@property (nonatomic,assign) BOOL  isShow ;
@property (nonatomic,strong) NSArray  * actions ;
@property (nonatomic,strong) NSMutableArray<UIButton *>  * itemBtnArray ;
//是否是休眠
@property (nonatomic,assign) BOOL  isDormant ;

@end

@implementation MoveMenuView


- (instancetype)initWithFrame:(CGRect)frame
{
    if (self  = [super initWithFrame:frame]) {
        self.bgView = [[UIView alloc]initWithFrame:self.bounds];
        self.bgView.backgroundColor = [UIColor clearColor];
        [self addSubview:self.bgView];
        self.contentView = [[UIView alloc]initWithFrame:self.bounds];
        self.contentView.backgroundColor = [UIColor clearColor];
        self.contentView.layer.masksToBounds = YES;
        [self addSubview:self.contentView];
        [self setUpTimer];
    }
    return self;
}

- (void)setMenuBgColor:(UIColor *)menuBgColor{
    _menuBgColor = menuBgColor;
    self.bgView.backgroundColor = _menuBgColor;
}

- (void)setMenuBgImage:(UIImage *)menuBgImage{
    _menuBgImage =menuBgImage ;
    self.bgView.layer.contents = (id)menuBgImage.CGImage;
}


+(instancetype)showSupView:(UIView *)supView locationInSupView:(CGPoint)pointLocation actions:(NSArray*)actions{
    MoveMenuView *menuView = [[MoveMenuView alloc]initWithFrame: CGRectMake(pointLocation.x,pointLocation.y, MENUVIEW_HEIGHT, MENUVIEW_HEIGHT)];
    menuView.supView = supView;
    menuView.actions= actions;
    [menuView setUpCrossBtn];
    [supView addSubview:menuView];
    return menuView;
}
- (void)setActions:(NSArray *)actions{
    _actions = actions;
    if (actions.count >0) {
        self.itemBtnArray = [NSMutableArray array];
        for (int i =0; i<actions.count; i++) {
            MoveMenuAction *action =  actions[i];
            UIButton *itemBtn = nil;
            if (action.itemHandler) {
                itemBtn = action.itemHandler();
                itemBtn.frame = CGRectMake(-(CGRectGetWidth(itemBtn.frame)-MENUVIEW_HEIGHT)/2.0,0, CGRectGetWidth(itemBtn.frame),CGRectGetHeight(itemBtn.frame));
                itemBtn.center = CGPointMake(itemBtn.center.x, MENUVIEW_HEIGHT/2.0);
            }else{
                itemBtn =[UIButton buttonWithType:UIButtonTypeCustom];
                [itemBtn setTitle:action.title forState:UIControlStateNormal];
                if (action.image) {
                    [itemBtn setImage:action.image  forState:UIControlStateNormal];
                }
                itemBtn.backgroundColor = [UIColor purpleColor];
                itemBtn.frame = CGRectMake(0,0, MENUVIEW_HEIGHT, MENUVIEW_HEIGHT);
            }
            [itemBtn addTarget:self action:@selector(itemAction:) forControlEvents:UIControlEventTouchUpInside];
            itemBtn.tag =1000+i;
            [self.contentView addSubview:itemBtn];
            [self.itemBtnArray addObject:itemBtn];
        }
    }
}

- (void)itemAction:(UIButton*)btn{
    NSInteger tagIndex =  btn.tag -1000;
    MoveMenuAction *action = self.actions[tagIndex];
    if(action.handler){
        action.handler();
        [self btnAction:self.centerBtn];
    }
}


- (void)setUpCrossBtn {
    _centerBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_centerBtn setImage:[UIImage imageNamed:@"index_btn_service"] forState:UIControlStateNormal];
    _centerBtn.backgroundColor = [UIColor redColor];
    _centerBtn.layer.masksToBounds = YES;
    _centerBtn.layer.cornerRadius =MENUVIEW_HEIGHT/2.0;
    _centerBtn.frame = self.bounds;
    [self addSubview:_centerBtn];
    [_centerBtn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(handlePan:)];
    [self addGestureRecognizer:pan];
    
    rightMargin = self.supView.bounds.size.width-30;
    leftMargin = 30;
    bottomMargin = self.supView.bounds.size.height-54;
    topMargin = SRARUS_HEIGHT;
    
    pathRef=CGPathCreateMutable();
    CGPathMoveToPoint(pathRef, NULL, leftMargin, topMargin);
    CGPathAddLineToPoint(pathRef, NULL, rightMargin, topMargin);
    CGPathAddLineToPoint(pathRef, NULL, rightMargin, bottomMargin);
    CGPathAddLineToPoint(pathRef, NULL, leftMargin, bottomMargin);
    CGPathAddLineToPoint(pathRef, NULL, leftMargin, topMargin);
    CGPathCloseSubpath(pathRef);
}


#pragma mark == 变成休眠
- (void )markDormant {
    [UIView animateWithDuration:0.25 animations:^{
        if (self.center.x >(self.supView.bounds.size.width/2.0)) {
            self.center = CGPointMake(self.supView.bounds.size.width-MENUVIEW_HEIGHT/4.0, self.center.y);
        }else{
            self.center = CGPointMake(MENUVIEW_HEIGHT/4.0, self.center.y);
        }
    }];
    self.alpha = 0.5;
    self.isDormant = YES;
}
/**
 创建定时器
 */
- (void)setUpTimer {
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    if (self.isShow) {
        dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 5.0*NSEC_PER_SEC),5.0*NSEC_PER_SEC, 0); //每秒执行
    }else{
        dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 3.0*NSEC_PER_SEC),3.0*NSEC_PER_SEC, 0); //每秒执行
    }
    dispatch_source_set_event_handler(_timer, ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            if (!self.isShow) {
                [self markDormant];
                if (self->_timer) {
                    dispatch_cancel(self->_timer);
                }
                self->_timer = nil;
            }else{
                if (!self.isDormant) {
                    [self btnAction:self.centerBtn];
                }
            }
    
        });
    });
    dispatch_resume(_timer);
    
}



#pragma mark == 隐藏按钮
-(void)hiddenItemBtn{
    [UIView animateWithDuration:0.25 animations:^{
        for (UIButton *itemBtn in  self.itemBtnArray) {
            itemBtn.frame = CGRectMake(-(CGRectGetWidth(itemBtn.frame)-MENUVIEW_HEIGHT)/2.0,-(CGRectGetHeight(itemBtn.frame)-MENUVIEW_HEIGHT)/2.0, CGRectGetWidth(itemBtn.frame), CGRectGetHeight(itemBtn.frame));
        }
        self.bgView.frame =CGRectMake(0,0, MENUVIEW_HEIGHT, MENUVIEW_HEIGHT);
    }completion:^(BOOL finished) {
        self.contentView.layer.masksToBounds = YES;
        
    }];
}
#pragma mark == 显示按钮
-(void)showItemBtn{
    if (self.center.x >(self.supView.bounds.size.width/2.0)) {
        [UIView animateWithDuration:0.25 animations:^{
            self.contentView.layer.masksToBounds = NO;
            CGFloat maxX= 0;
            for (int i =0 ; i< self.itemBtnArray.count ; i++) {
                UIButton *itemBtn = self.itemBtnArray[i];
                maxX = maxX+CGRectGetWidth(itemBtn.frame)+MENUVIEW_ITEM_SPACE;
                itemBtn.frame =CGRectMake( -maxX,0, CGRectGetWidth(itemBtn.frame), CGRectGetHeight(itemBtn.frame));
                itemBtn.center = CGPointMake(itemBtn.center.x, MENUVIEW_HEIGHT/2.0);
            }
            CGFloat bgViewWidth = maxX;
            self.bgView.frame =CGRectMake(-bgViewWidth-MENUVIEW_BGVIEW_BEYOND,0, bgViewWidth+CGRectGetWidth(self.itemBtnArray.lastObject.frame)+MENUVIEW_BGVIEW_BEYOND, MENUVIEW_HEIGHT);
        }];
    }else{
        [UIView animateWithDuration:0.25 animations:^{
            self.contentView.layer.masksToBounds = NO;
            UIButton *beforeBtn =nil;
            for (int i = 0; i< self.itemBtnArray.count ; i++) {
                UIButton *itemBtn = self.itemBtnArray[i];
                if (beforeBtn == nil) {
                    itemBtn.frame =CGRectMake(CGRectGetWidth(itemBtn.frame)+MENUVIEW_ITEM_SPACE,0,CGRectGetWidth(itemBtn.frame),CGRectGetHeight(itemBtn.frame));
                }else{
                    itemBtn.frame =CGRectMake(CGRectGetMaxX(beforeBtn.frame)+MENUVIEW_ITEM_SPACE,0,CGRectGetWidth(itemBtn.frame),CGRectGetHeight(itemBtn.frame));
                }
                itemBtn.center = CGPointMake(itemBtn.center.x, MENUVIEW_HEIGHT/2.0);
                beforeBtn = itemBtn;
            }
            CGFloat bgViewWidth =CGRectGetMaxX(beforeBtn.frame);
            self.bgView.frame =CGRectMake(0,0, bgViewWidth+MENUVIEW_BGVIEW_BEYOND, MENUVIEW_HEIGHT);
        }];
        
    }
}

- (void)btnAction:(UIButton *)btn{
    if (self.isDormant) {
        self.alpha = 1;
        self.isDormant = NO;
        [UIView animateWithDuration:0.25 animations:^{
            if (self.center.x >(self.supView.bounds.size.width/2.0)) {
                self.center = CGPointMake(self.supView.bounds.size.width-MENUVIEW_HEIGHT/2.0, self.center.y);
            }else{
                self.center = CGPointMake( MENUVIEW_HEIGHT/2.0, self.center.y);
            }
        }];
    }else{
        
        if (self.isShow) {
            [self hiddenItemBtn];
        }else{
            [self showItemBtn];
        }
        self.isShow = !self.isShow;

    }
    if (self->_timer) {
        dispatch_cancel(self->_timer);
    }
    self->_timer = nil;
    [self setUpTimer];
    
}



- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    UIView *view = [super hitTest:point withEvent:event];
    if (view == nil) {
        for (UIView *subView in self.subviews) {
            if (subView  == self.contentView) {
                for (UIView *contentViewSubView in self.contentView.subviews) {
                    CGPoint p = [contentViewSubView convertPoint:point fromView:self.contentView];
                    if (CGRectContainsPoint(contentViewSubView.bounds, p)) {
                        view = contentViewSubView;
                    }
                }
            }else{
                CGPoint p = [subView convertPoint:point fromView:self];
                if (CGRectContainsPoint(subView.bounds, p)) {
                    view = subView;
                }
            }
            
        }
    }
    return view;
}





#pragma mark - 手势
- (void)handlePan:(UIPanGestureRecognizer *)pan
{
    if (self.isShow) {
        return;
    }
    self.alpha = 1;
    self.isDormant = NO;
    if (pan.state == UIGestureRecognizerStateBegan) {
        beginPoint = [pan locationInView:self.supView];
    }else if (pan.state == UIGestureRecognizerStateChanged){
        CGPoint nowPoint = [pan locationInView:self.supView];
        float offsetX = nowPoint.x - beginPoint.x;
        float offsetY = nowPoint.y - beginPoint.y;
        CGPoint centerPoint = CGPointMake(beginPoint.x + offsetX, beginPoint.y + offsetY);
        if (CGPathContainsPoint(pathRef, NULL, centerPoint, NO))
        {
            self.center = centerPoint;
        }else{
            if (centerPoint.y>bottomMargin)
            {
                if (centerPoint.x<rightMargin&&centerPoint.x>leftMargin) {
                    self.center = CGPointMake(beginPoint.x + offsetX, bottomMargin);
                }
            }
            else if (centerPoint.y<topMargin)
            {
                if (centerPoint.x<rightMargin&&centerPoint.x>leftMargin) {
                    self.center = CGPointMake(beginPoint.x + offsetX, topMargin);
                }
            }
            else if (centerPoint.x>rightMargin)
            {
                self.center = CGPointMake(rightMargin, beginPoint.y + offsetY);
            }
            else if (centerPoint.x<leftMargin)
            {
                self.center = CGPointMake(leftMargin, beginPoint.y + offsetY);
            }
        }
    }else if (pan.state == UIGestureRecognizerStateEnded ){
        
        if (self.center.x >(self.supView.bounds.size.width/2.0)) {
            [UIView animateWithDuration:0.25 animations:^{
                self.center = CGPointMake(self.supView.bounds.size.width-MENUVIEW_HEIGHT/2.0, self.center.y);
            }completion:^(BOOL finished) {
                if (self->_timer) {
                    dispatch_cancel(self->_timer);
                }
                self->_timer = nil;
                [self setUpTimer];
                
            }];
        }else{
            [UIView animateWithDuration:0.25 animations:^{
                self.center = CGPointMake( MENUVIEW_HEIGHT/2.0, self.center.y);
            }completion:^(BOOL finished) {
                if (self->_timer) {
                    dispatch_cancel(self->_timer);
                }
                self->_timer = nil;
                [self setUpTimer];
            }];
        }
    }else if (pan.state == UIGestureRecognizerStateFailed){
        
    }
}
@end





